from ShopOL.settings import alipay_private_path, alipay_key_path, return_url, notify_url, alipay_open_api
from goods.models import Goods
from goods.serializers import GoodSerializer
import time, random
from .models import ShoppingCart, OrderInfo, OrderGoods
from goods.serializers import GoodSerializer
from rest_framework import serializers
from utils.alipay import AliPay


class ShopCartDetailSerializer(serializers.ModelSerializer):
    goods = GoodSerializer(many=False)

    class Meta:
        model = ShoppingCart
        fields = '__all__'


class ShopCartSerializer(serializers.Serializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    nums = serializers.IntegerField(required=True, min_value=1, error_messages={
        "min_value": "商品数量不能小于1",
        "required": "请选择购买数量"
    }, help_text='购买数量')
    goods = serializers.PrimaryKeyRelatedField(required=True, queryset=Goods.objects.all(), help_text='商品')

    def update(self, instance, validated_data):
        # 修改商品数量
        instance.nums = validated_data['nums']
        instance.save()
        return instance

    def create(self, validated_data):
        user = self.context['request'].user
        nums = validated_data['nums']
        goods = validated_data['goods']
        existed = ShoppingCart.objects.filter(user=user, goods=goods).first()
        if existed:
            existed.nums += nums
            existed.save()
        else:
            existed = ShoppingCart.objects.create(**validated_data)
        return existed


class OrderInfoSerializes(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    order_sn = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    pay_status = serializers.CharField(read_only=True)
    pay_time = serializers.CharField(read_only=True)
    add_time = serializers.CharField(read_only=True)
    alipay_url = serializers.SerializerMethodField(read_only=True)

    def get_alipay_url(self, obj):
        alipay = AliPay(
            appid="2016093000630230",
            app_notify_url=notify_url,
            app_private_key_path=alipay_private_path,
            alipay_public_key_path=alipay_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            debug=True,  # 默认False,
            return_url=return_url
        )
        url = alipay.direct_pay(
            subject="订单号:"+obj.order_sn,
            out_trade_no=obj.order_sn,
            total_amount=obj.order_mount,
        )
        re_url = alipay_open_api.format(data=url)
        return re_url

    def generate_order_sn(self):
        random_int = random.Random()
        order_sn = "{time_str}{user_id}{ran_str}".format(time_str=time.strftime("%Y%m%d%H%M%S"),
                                                         user_id=self.context["request"].user.id,
                                                         ran_str=random_int.randint(100, 999))
        return order_sn

    def validate(self, attrs):
        attrs['order_sn'] = self.generate_order_sn()
        return attrs

    class Meta:
        model = OrderInfo
        fields = '__all__'


class OrderGoodsSerializes(serializers.ModelSerializer):
    goods = GoodSerializer(many=False)

    class Meta:
        model = OrderGoods
        fields = '__all__'


class OrderDetailInfoSerializes(serializers.ModelSerializer):
    goods = OrderGoodsSerializes(many=True)
    alipay_url = serializers.SerializerMethodField(read_only=True)

    def get_alipay_url(self, obj):
        alipay = AliPay(
            appid="2016093000630230",
            app_notify_url=return_url,
            app_private_key_path=alipay_private_path,
            alipay_public_key_path=alipay_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            debug=True,  # 默认False,
            return_url=return_url
        )
        url = alipay.direct_pay(
            subject="订单号:" + obj.order_sn,
            out_trade_no=obj.order_sn,
            total_amount=obj.order_mount,
        )
        re_url = alipay_open_api.format(data=url)
        return re_url

    class Meta:
        model = OrderInfo
        fields = '__all__'
